package org.csu.small.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Sets;
import org.csu.small.common.Constant;
import org.csu.small.common.UniformResponse;
import org.csu.small.entity.Category;
import org.csu.small.entity.Product;
import org.csu.small.persistence.CategoryMapper;
import org.csu.small.persistence.ProductMapper;
import org.csu.small.service.ICategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service("categoryService")
public class CategoryServiceImpl implements ICategoryService {

    private Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public UniformResponse<Category> getCategoryInfo(Integer categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        if (category == null){
            return UniformResponse.createForErrorMessage("分类不存在");
        }
        return UniformResponse.createForSuccess(category);
    }

    @Override
    public UniformResponse<String> addCategory(Category category) {
        int rows = categoryMapper.selectCount(Wrappers.<Category>query().eq("name", category.getName()));
        if (rows > 0) {
            return UniformResponse.createForErrorMessage("类别名已存在");
        }
        category.setStatus(category.getStatus() == null ? 0 : category.getStatus());
        category.setSortOrder(category.getSortOrder() == null ? 0 : category.getSortOrder());
        rows = categoryMapper.insert(category);
        if (rows == 0) {
            return UniformResponse.createForErrorMessage("添加类别失败");
        }
        return UniformResponse.createForSuccessMessage("添加类别成功");
    }

    @Override
    public UniformResponse<String> editCategory(Category category) {
        int rows = categoryMapper.updateById(category);
        if (rows == 0) {
            return UniformResponse.createForErrorMessage("更新类别信息失败");
        }
        return UniformResponse.createForSuccessMessage("更新类别信息成功");
    }

    @Override
    public UniformResponse<List<Category>> getCategory(Integer categoryId) {
        QueryWrapper<Category> query = new QueryWrapper<>();
        query.eq("parent_id", categoryId);
        List<Category> categoryList = categoryMapper.selectList(query);
        if (CollectionUtils.isEmpty(categoryList)) {
            logger.info("查找子分类时没有发现子分类");
        }
        return UniformResponse.createForSuccess(categoryList);
    }

    @Override
    public UniformResponse<List<Category>> getDeepCategory(Integer categoryId) {
        Set<Category> categorySet = Sets.newHashSet();
        findChildCategory(categoryId, categorySet);

        return UniformResponse.createForSuccess(new ArrayList<>(categorySet));
    }

    @Override
    public UniformResponse<String> deleteCategory(Integer categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        if (category.getParentId() != 0){
            categoryMapper.deleteById(categoryId);
            deleteCategoryProducts(categoryId, category.getParentId());
        }else {
            deleteCategoryProducts(categoryId, -1);
            // 查找父分类下的子分类
            Set<Category> categoryChildSet = Sets.newHashSet();
            findChildCategory(categoryId, categoryChildSet);
            for (Category categoryChild : categoryChildSet){
                categoryMapper.deleteById(categoryChild.getId());
                deleteCategoryProducts(categoryChild.getId(), -1);
            }
        }
        return UniformResponse.createForSuccessMessage("删除品类成功");
    }

    // 将该分类下所有商品改为新类别id
    private void deleteCategoryProducts(Integer categoryId, Integer newId){
        QueryWrapper<Product> query = new QueryWrapper<>();
        query.eq("category_id", categoryId);
        List<Product> products = productMapper.selectList(query);
        for (Product product : products){
            product.setCategoryId(newId);
            productMapper.updateById(product);
        }
    }

    private Set<Category> findChildCategory(Integer categoryId, Set<Category> categorySet) {
        Category category = categoryMapper.selectById(categoryId);
        if (category != null) {
            categorySet.add(category);
        }
        QueryWrapper<Category> query = new QueryWrapper<>();
        query.eq("parent_id", categoryId);
        List<Category> categoryList = categoryMapper.selectList(query);
        for (Category categoryItem : categoryList) {
            findChildCategory(categoryItem.getId(), categorySet);
        }

        return categorySet;
    }

}

